<template>
  <div>
    <div style="position: relative">
      <video ref="screenVideo" width="1202" height="780" controls></video>
      <canvas
        ref="overlayCanvas"
        width="1202"
        height="780"
        style="position: absolute; top: 0; left: 0"
      ></canvas>
    </div>
    <div>
      <button @click="startSharing">共享屏幕</button>
    </div>
    <div>识别结果：{{ recognitionResult }}</div>
  </div>
</template>

<script setup>
import { ref } from "vue";
import Tesseract from "tesseract.js";
import { PRICES } from "@/config";
import keys from "lodash/keys";

// 定义视频元素的引用
const screenVideo = ref(null);
// 存储文字识别结果
const recognitionResult = ref("");
const overlayCanvas = ref(null);

// 绘制文字标识
const drawTextMarkers = (text, canvasWidth, canvasHeight) => {
  const ctx = overlayCanvas.value.getContext("2d");
  ctx.clearRect(0, 0, canvasWidth, canvasHeight);
  ctx.strokeStyle = "red";
  ctx.lineWidth = 2;
  // 简单假设每行文字均匀分布在整个图像高度上
  const lines = text.split("\n");
  const lineHeight = canvasHeight / lines.length;
  lines.forEach((line, index) => {
    if (line.trim() !== "") {
      ctx.strokeRect(0, index * lineHeight, canvasWidth, lineHeight);
    }
  });
};

// 图像预处理函数
const preprocessImage = (canvas) => {
  const ctx = canvas.getContext("2d");
  const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
  const data = imageData.data;
  // 灰度化
  for (let i = 0; i < data.length; i += 4) {
    const avg = (data[i] + data[i + 1] + data[i + 2]) / 3;
    data[i] = avg;
    data[i + 1] = avg;
    data[i + 2] = avg;
  }
  // 简单的二值化
  const threshold = 128;
  for (let i = 0; i < data.length; i += 4) {
    data[i] = data[i] > threshold ? 255 : 0;
    data[i + 1] = data[i + 1] > threshold ? 255 : 0;
    data[i + 2] = data[i + 2] > threshold ? 255 : 0;
  }
  ctx.putImageData(imageData, 0, 0);
  return canvas;
};

const extractKeywords = async (tt) => {
  const keywords = keys(PRICES);
  const result = [];
  for (const keyword of keywords) {
    if (tt.includes(keyword)) {
      result.push(keyword);
    }
  }
  const data = [];
  result.forEach((element) => {
    data.push({
      name: element,
      value: PRICES[element],
    });
  });

  return data;
};

const animationFrameId = ref(null);
let stream = null;
const isSharing = ref(false);

const stopSharingAndRecognition = () => {
  isSharing.value = false;
  if (animationFrameId.value) {
    cancelAnimationFrame(animationFrameId.value);
    animationFrameId.value = null;
  }
  if (stream) {
    stream.getVideoTracks().forEach((track) => track.stop());
    stream = null;
  }
};
// 开始共享屏幕的函数
const startSharing = async () => {
  isSharing.value = true;
  try {
    // 使用 getDisplayMedia 获取屏幕共享流
    stream = await navigator.mediaDevices.getDisplayMedia({
      video: true,
      audio: false, // 这里假设不共享音频，可根据需求修改
    });

    // 将流赋值给视频元素的 srcObject 属性
    screenVideo.value.srcObject = stream;

    // 播放视频
    await screenVideo.value.play();

    const tick = async () => {
      if (animationFrameId.value) {
        cancelAnimationFrame(animationFrameId.value);
      }
      if (screenVideo.value) {
        const canvas = document.createElement("canvas");
        canvas.width = screenVideo.value.videoWidth;
        canvas.height = screenVideo.value.videoHeight;
        const ctx = canvas.getContext("2d");
        ctx.drawImage(screenVideo.value, 0, 0, canvas.width, canvas.height);

        // 图像预处理
        const preprocessedCanvas = preprocessImage(canvas);
        const imageDataUrl = preprocessedCanvas.toDataURL("image/jpeg");

        try {
          const { data } = await Tesseract.recognize(imageDataUrl, "chi_sim", {
            logger: (m) => {},
            // 启用页面分割模式，这里选择自动模式
            tessedit_pageseg_mode: 3,
            // 提高识别的可信度阈值
            tessedit_char_whitelist:
              "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\u4e00-\u9fa5",
            // 其他可能的配置参数
            user_defined_dpi: 300,
          });
          // 去除文字空格，保留换行符
          const tt = data.text.replace(/[^\u4e00-\u9fa50-9]/g, "");
          // const extractKeywordsResult = await extractKeywords(result);
          recognitionResult.value = tt;
          console.log("xxxxx:", data.text.split("\n"));
          if (isSharing.value) {
            animationFrameId.value = requestAnimationFrame(tick);
          }
        } catch (tesseractError) {
          console.error("文字识别出错:", tesseractError);
        }
      }
    };

    // 当视频停止播放时，清除requestAnimationFrame
    screenVideo.value.addEventListener("ended", stopSharingAndRecognition);
    stream.getVideoTracks()[0].addEventListener("ended", stopSharingAndRecognition);
    animationFrameId.value = requestAnimationFrame(tick);
  } catch (error) {
    stopSharingAndRecognition();
  }
};
</script>

<style scoped>
/* 可以添加一些样式 */
</style>